<?php

namespace App\Services\Base;
use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Models\Base\Group;
use App\Models\Base\Resource;
use App\Models\Role\Role;
use App\Models\Role\RoleResourceBind;
use App\Params\Backend\GroupListParams;
use App\Params\Backend\GroupUpdateParam;
use App\Params\Backend\ResourceListParam;
use App\Repository\GradeRepository;
use App\Repository\GroupRepository;
use App\Services\BaseService;

/**
 * 系统分组业务类
 *
 * @author WangBin
 * @date 2021-09-11
 * @package App\Http\Services
 */
class GroupService extends BaseService
{
    /**
     * 获取分组列表
     *
     * @param
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getList(GroupListParams $param)
    {
        return $this->toList(GroupRepository::getInstance()->getList($param->toArray()), $param->getPage(), $param->getPageSize());
    }

    /**
     * 保存资源
     *
     * @param GroupUpdateParam $data
     * @return bool
     * @throws BusinessException
     */
    public function update(GroupUpdateParam $data)
    {
        if($data->getGroupId()) {
            $group = Group::getById($data->getGroupId());
            if(is_null($group)) {
                throw new BusinessException(ResponseCode::GROUP_NOT_FOUND);
            }
        }
        // 检查分组名称唯一
        $check = Group::checkGroupName($data->getGroupName(), $data->getType(), $data->getGroupId());
        if($check) {
            throw new BusinessException(ResponseCode::SAVE_FAIL, ['error' => '分组名称重复']);
        }
        return Group::saveData($data);
    }

    /**
     * 分组详情
     *
     * @param int $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws BusinessException
     */
    public function get(int $id)
    {
        $data = GroupRepository::getInstance()->getById($id);
        if(is_null($data)) {
            throw new BusinessException(ResponseCode::RESOURCE_NOT_FOUND);
        }
        return $data;
    }

    /**
     * 删除分组
     *
     * @param int $groupId
     * @return mixed
     * @throws
     */
    public function delete(int $groupId)
    {
        return GroupRepository::getInstance()->delete($groupId);
    }

    /**
     * 停用/启用分组
     *
     * @param int $id
     * @return int
     * @throws BusinessException
     */
    public function enable(int $id)
    {
        $resource = Resource::getById($id);
        if(is_null($resource)) {
            throw new BusinessException(ResponseCode::RESOURCE_NOT_FOUND);
        }
        $isActive = $resource->is_active == 0 ? 1 : 0;
        return Resource::enable($id, $isActive);
    }
}
